// 工单服务 - 连接后端API
import axios from 'axios'
import config from '../config'

const API_BASE_URL = config.API_BASE_URL

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: config.API_TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    console.log('🔧 [Tickets API] 请求拦截器触发')
    console.log('🔧 [Tickets API] 请求URL:', config.url)
    console.log('🔧 [Tickets API] baseURL:', config.baseURL)
    console.log('🔧 [Tickets API] 完整URL:', `${config.baseURL}${config.url}`)
    console.log('🔧 [Tickets API] 请求方法:', config.method)
    console.log('🔧 [Tickets API] 请求参数:', config.params)
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('🔧 [Tickets API] ✅ 已添加Authorization头')
    } else {
      console.warn('⚠️ [Tickets API] ⚠️ 未找到Token，请求可能失败')
    }
    
    return config
  },
  error => {
    console.error('❌ [Tickets API] 请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  response => {
    // 后端返回格式: { success: true, data: {...}, message: "...", timestamp: "...", code: 200 }
    // 直接返回 response.data，这样在 service 中可以直接访问 success、data 等字段
    return response.data
  },
  error => {
    console.error('❌ [Tickets API] 请求失败:', error)
    
    // 输出详细的错误信息
    if (error.response) {
      console.error('❌ [Tickets API] HTTP状态:', error.response.status, error.response.statusText)
      console.error('❌ [Tickets API] 响应数据:', error.response.data)
      console.error('❌ [Tickets API] 请求URL:', error.config?.url)
      console.error('❌ [Tickets API] 请求方法:', error.config?.method)
      console.error('❌ [Tickets API] 请求参数:', error.config?.params)
    } else if (error.request) {
      console.error('❌ [Tickets API] 请求已发送但未收到响应')
      console.error('❌ [Tickets API] 可能的原因:')
      console.error('   1. 后端服务未启动 (检查 http://localhost:9090)')
      console.error('   2. 网络连接问题')
      console.error('   3. CORS跨域问题')
      console.error('   4. API地址配置错误:', API_BASE_URL)
    } else {
      console.error('❌ [Tickets API] 请求配置错误:', error.message)
    }
    
    // 处理认证错误
    if (error.response?.status === 401) {
      console.error('🔒 [Tickets API] 认证失败！Token可能无效或已过期')
      console.error('💡 建议: 请重新登录')
      
      // 尝试刷新token
      try {
        const AuthService = require('./auth').AuthService
        AuthService.refreshToken().then(() => {
          console.log('✅ Token刷新成功，重试请求')
        }).catch(() => {
          console.log('❌ Token刷新失败，强制重新登录')
          AuthService.forceReLogin()
        })
      } catch (e) {
        console.warn('⚠️ 无法加载AuthService:', e)
      }
      
      const authError = new Error('AUTHENTICATION_FAILED')
      authError.status = 401
      authError.isAuthError = true
      authError.message = '认证失败，请重新登录'
      return Promise.reject(authError)
    }
    
    // 处理权限错误
    if (error.response?.status === 403) {
      console.error('🚫 [Tickets API] 权限不足！当前用户可能没有访问工单列表的权限')
      const permissionError = new Error('PERMISSION_DENIED')
      permissionError.status = 403
      permissionError.isPermissionError = true
      permissionError.message = '权限不足，无法访问工单列表'
      return Promise.reject(permissionError)
    }
    
    // 处理400错误
    if (error.response?.status === 400) {
      console.error('❌ [Tickets API] 请求参数错误！')
      const badRequestError = new Error(error.response?.data?.message || '请求参数错误')
      badRequestError.status = 400
      badRequestError.isBadRequest = true
      return Promise.reject(badRequestError)
    }
    
    // 处理服务器错误
    if (error.response?.status >= 500) {
      console.error('🔥 [Tickets API] 服务器内部错误！')
      const serverError = new Error('SERVER_ERROR')
      serverError.status = error.response.status
      serverError.isServerError = true
      serverError.message = '服务器错误，请稍后重试'
      return Promise.reject(serverError)
    }
    
    // 网络错误
    if (!error.response && error.request) {
      const networkError = new Error('NETWORK_ERROR')
      networkError.message = '无法连接到服务器，请检查网络连接和后端服务状态'
      networkError.isNetworkError = true
      return Promise.reject(networkError)
    }
    
    return Promise.reject(error)
  }
)

export const TicketService = {
  // 获取工单列表
  async list(params = {}) {
    try {
      console.log('📤 [TicketService.list] 发送请求，参数:', params)
      console.log('📤 [TicketService.list] API_BASE_URL:', API_BASE_URL)
      console.log('📤 [TicketService.list] 完整URL:', `${API_BASE_URL}/tickets`)
      console.log('📤 [TicketService.list] 请求参数:', params)
      
      // 检查token
      const token = localStorage.getItem('token')
      console.log('📤 [TicketService.list] Token存在:', !!token)
      if (token) {
        console.log('📤 [TicketService.list] Token长度:', token.length)
      }
      
      // 添加缓存控制，防止浏览器缓存
      // 注意：增加超时时间，因为工单查询可能需要更长时间
      const timeout = config.API_TIMEOUT * 2 || 20000 // 默认20秒
      console.log('📤 [TicketService.list] 请求超时设置:', timeout + 'ms')
      
      const response = await apiClient.get('/tickets', { 
        params,
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        },
        timeout: timeout,
        // 添加请求开始时间
        validateStatus: function (status) {
          console.log('📥 [TicketService.list] 收到响应状态:', status)
          return status >= 200 && status < 300 // 默认行为
        }
      })
      
      console.log('📥 [TicketService.list] 收到响应:', response)
      console.log('📥 [TicketService.list] 响应类型:', typeof response)
      console.log('📥 [TicketService.list] response.success:', response?.success)
      console.log('📥 [TicketService.list] response.data:', response?.data)
      
      // 后端返回格式: { success: true, data: {content: [...], page: 0, totalElements: 30, ...} }
      // 注意：后端 PageResponse 的 page 字段是 0 基索引（使用 page.getNumber()）
      if (response && response.success) {
        const data = response.data || { content: [], totalElements: 0, page: 0, size: 20 }
        console.log('✅ [TicketService.list] 解析后的数据:', data)
        console.log('✅ [TicketService.list] data.content 类型:', Array.isArray(data.content) ? '数组' : typeof data.content)
        console.log('✅ [TicketService.list] data.content 长度:', Array.isArray(data.content) ? data.content.length : 'N/A')
        
        // 将后端返回的 0 基索引 page 转换为 1 基索引（前端使用）
        if (data.page !== undefined && typeof data.page === 'number') {
          data.page = data.page + 1
        }
        return data
      } else {
        console.error('❌ [TicketService.list] 响应格式不正确:', response)
        throw new Error(response?.message || '获取工单列表失败：响应格式不正确')
      }
    } catch (error) {
      console.error('❌ [TicketService.list] 获取工单列表失败:', error)
      // 输出更详细的错误信息以便调试
      if (error.response) {
        console.error('❌ [TicketService.list] 响应状态:', error.response.status)
        console.error('❌ [TicketService.list] 响应数据:', error.response.data)
        console.error('❌ [TicketService.list] 响应头:', error.response.headers)
      } else if (error.request) {
        console.error('❌ [TicketService.list] 请求已发送但未收到响应')
      } else {
        console.error('❌ [TicketService.list] 请求配置错误:', error.message)
      }
      throw error
    }
  },

  // 获取工单详情
  async get(id) {
    try {
      const response = await apiClient.get(`/tickets/${id}`)
      return response.success ? response.data : null
    } catch (error) {
      console.error('获取工单详情失败:', error)
      throw new Error(error.response?.data?.message || '获取工单详情失败')
    }
  },

  // 根据工单编号获取工单
  async getByNumber(ticketNumber) {
    try {
      const response = await apiClient.get(`/tickets/number/${ticketNumber}`)
      return response.success ? response.data : null
    } catch (error) {
      console.error('获取工单详情失败:', error)
      throw new Error(error.response?.data?.message || '获取工单详情失败')
    }
  },

  // 创建工单
  async create(payload) {
    const requestId = `REQ-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    
    try {
      console.log('═══════════════════════════════════════════════════')
      console.log(`🚀 [${requestId}] 开始创建工单`)
      console.log(`📋 [${requestId}] 原始表单数据:`, JSON.stringify(payload, null, 2))
      
      // 【安全修复】不再从 localStorage 获取用户ID
      // 用户身份由后端从 JWT token 中自动提取，确保前后端身份一致
      console.log(`🔒 [${requestId}] 用户身份将由后端从 Token 中自动获取（安全）`)
      
      // 构建请求数据
      const requestData = {
        title: payload.title,
        description: payload.description,
        descriptionDetail: payload.descriptionDetail,
        categoryId: payload.categoryId,
        priority: payload.priority || 'MEDIUM'
        // 移除 creatorId 和 customerId，由后端从 SecurityContext 获取
      }
      
      console.log(`📤 [${requestId}] 即将发送的请求数据:`, JSON.stringify(requestData, null, 2))
      console.log(`🌐 [${requestId}] 请求URL: POST /api/tickets`)
      console.log(`⏰ [${requestId}] 请求时间:`, new Date().toISOString())
      
      const startTime = Date.now()
      const response = await apiClient.post('/tickets', requestData)
      const endTime = Date.now()
      
      console.log(`⏱️ [${requestId}] 请求耗时: ${endTime - startTime}ms`)
      console.log(`📥 [${requestId}] 收到响应:`, JSON.stringify(response, null, 2))
      console.log(`📊 [${requestId}] 响应状态:`, response.success ? '成功' : '失败')
      
      if (response.success) {
        console.log(`✅ [${requestId}] 工单创建成功！`)
        console.log(`🎫 [${requestId}] 返回的工单数据:`, JSON.stringify(response.data, null, 2))
        console.log(`🆔 [${requestId}] 工单ID: ${response.data?.id}`)
        console.log(`🔢 [${requestId}] 工单编号: ${response.data?.ticketNumber}`)
        console.log('═══════════════════════════════════════════════════')
        return response.data
      } else {
        console.error(`❌ [${requestId}] 响应标记为失败:`, response.message || response.error)
        console.log('═══════════════════════════════════════════════════')
        return null
      }
    } catch (error) {
      console.error('═══════════════════════════════════════════════════')
      console.error(`❌ [${requestId}] 创建工单失败`)
      console.error(`❌ [${requestId}] 错误类型:`, error.constructor.name)
      console.error(`❌ [${requestId}] 错误消息:`, error.message)
      console.error(`❌ [${requestId}] 错误堆栈:`, error.stack)
      
      if (error.response) {
        console.error(`❌ [${requestId}] HTTP状态码:`, error.response.status)
        console.error(`❌ [${requestId}] 响应头:`, JSON.stringify(error.response.headers, null, 2))
        console.error(`❌ [${requestId}] 响应数据:`, JSON.stringify(error.response.data, null, 2))
      } else if (error.request) {
        console.error(`❌ [${requestId}] 请求已发送但未收到响应`)
        console.error(`❌ [${requestId}] 请求详情:`, error.request)
      } else {
        console.error(`❌ [${requestId}] 请求配置错误:`, error.config)
      }
      console.error('═══════════════════════════════════════════════════')
      throw error
    }
  },



  // 批量操作API方法
  async batchAssign(ticketIds, assigneeId) {
    try {
      const response = await apiClient.post('/tickets/batch/assign', {
        ticketIds,
        assigneeId
      })
      
      if (response.success) {
        console.log('✅ 批量指派成功')
        return response.data
      } else {
        throw new Error(response.message || '批量指派失败')
      }
    } catch (error) {
      console.error('❌ 批量指派失败:', error)
      throw error
    }
  },

  async batchUpdateStatus(ticketIds, status, note) {
    try {
      const response = await apiClient.post('/tickets/batch/status', {
        ticketIds,
        status,
        note
      })
      
      if (response.success) {
        console.log('✅ 批量更新状态成功')
        return response.data
      } else {
        throw new Error(response.message || '批量更新状态失败')
      }
    } catch (error) {
      console.error('❌ 批量更新状态失败:', error)
      throw error
    }
  },

  async batchDelete(ticketIds) {
    try {
      const response = await apiClient.post('/tickets/batch/delete', {
        ticketIds
      })
      
      if (response.success) {
        console.log('✅ 批量删除成功')
        return response.data
      } else {
        throw new Error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('❌ 批量删除失败:', error)
      throw error
    }
  },

  // 更新工单状态
  async updateStatus(id, status, note = '') {
    try {
      const response = await apiClient.put(`/tickets/${id}/status`, {
        status: status,
        note: note
      })
      return response.success ? response.data : null
    } catch (error) {
      console.error('更新工单状态失败:', error)
      throw new Error(error.response?.data?.message || '更新工单状态失败')
    }
  },

  // 分配工单
  async assign(id, agentId, agentName) {
    try {
      const response = await apiClient.put(`/tickets/${id}/assign`, {
        assigneeId: agentId
      })
      return response.success ? response.data : null
    } catch (error) {
      console.error('分配工单失败:', error)
      throw new Error(error.response?.data?.message || '分配工单失败')
    }
  },

  // 更新工单优先级
  async updatePriority(id, priority) {
    try {
      const response = await apiClient.put(`/tickets/${id}/priority`, {
        priority: priority
      })
      return response.data
    } catch (error) {
      console.error('更新工单优先级失败:', error)
      throw new Error(error.response?.data?.message || '更新工单优先级失败')
    }
  },

  // 搜索工单
  async search(params = {}) {
    try {
      const response = await apiClient.get('/tickets/search', { params })
      return response.data || []
    } catch (error) {
      console.error('搜索工单失败:', error)
      throw new Error(error.response?.data?.message || '搜索工单失败')
    }
  },

  // 获取用户的工单
  async getUserTickets(userId, params = {}) {
    try {
      const response = await apiClient.get(`/tickets/user/${userId}`, { params })
      return response.data || []
    } catch (error) {
      console.error('获取用户工单失败:', error)
      throw new Error(error.response?.data?.message || '获取用户工单失败')
    }
  },

  // 获取分配给用户的工单
  async getAssignedTickets(userId, params = {}) {
    try {
      const response = await apiClient.get(`/tickets/assigned/${userId}`, { params })
      return response.data || []
    } catch (error) {
      console.error('获取分配工单失败:', error)
      throw new Error(error.response?.data?.message || '获取分配工单失败')
    }
  },

  // 获取即将到期的工单
  async getUpcomingDueTickets(hours = 24) {
    try {
      const response = await apiClient.get('/tickets/upcoming-due', {
        params: { hours }
      })
      return response.data || []
    } catch (error) {
      console.error('获取即将到期工单失败:', error)
      throw new Error(error.response?.data?.message || '获取即将到期工单失败')
    }
  },

  // 获取超时工单
  async getOverdueTickets(hours = 72, status = null, params = {}) {
    try {
      const response = await apiClient.get('/tickets/overdue', {
        params: { hours, status, ...params }
      })
      return response.data || []
    } catch (error) {
      console.error('获取超时工单失败:', error)
      throw new Error(error.response?.data?.message || '获取超时工单失败')
    }
  },

  // 获取工单统计
  async getStats(customerId = null, assigneeId = null) {
    try {
      let response
      if (customerId) {
        response = await apiClient.get(`/tickets/stats/customer/${customerId}`)
      } else if (assigneeId) {
        response = await apiClient.get(`/tickets/stats/assignee/${assigneeId}`)
      } else {
        throw new Error('需要提供customerId或assigneeId')
      }
      return response.data || []
    } catch (error) {
      console.error('获取工单统计失败:', error)
      throw new Error(error.response?.data?.message || '获取工单统计失败')
    }
  },

  // 获取工单趋势数据
  async getTrendData(startDate = null, endDate = null) {
    try {
      const response = await apiClient.get('/tickets/trend', {
        params: { startDate, endDate }
      })
      return response.data || []
    } catch (error) {
      console.error('获取趋势数据失败:', error)
      throw new Error(error.response?.data?.message || '获取趋势数据失败')
    }
  },

  // 获取工单状态分布
  async getStatusDistribution() {
    try {
      const response = await apiClient.get('/tickets/distribution/status')
      return response.data || []
    } catch (error) {
      console.error('获取状态分布失败:', error)
      throw new Error(error.response?.data?.message || '获取状态分布失败')
    }
  },

  // 获取工单优先级分布
  async getPriorityDistribution() {
    try {
      const response = await apiClient.get('/tickets/distribution/priority')
      return response.data || []
    } catch (error) {
      console.error('获取优先级分布失败:', error)
      throw new Error(error.response?.data?.message || '获取优先级分布失败')
    }
  },

  // 获取平均解决时间
  async getAverageResolutionTime() {
    try {
      const response = await apiClient.get('/tickets/metrics/average-resolution-time')
      return response.data
    } catch (error) {
      console.error('获取平均解决时间失败:', error)
      throw new Error(error.response?.data?.message || '获取平均解决时间失败')
    }
  },

  // 获取SLA达成率
  async getSlaComplianceRate(slaHours = 72) {
    try {
      const response = await apiClient.get('/tickets/metrics/sla-compliance', {
        params: { slaHours }
      })
      return response.data
    } catch (error) {
      console.error('获取SLA达成率失败:', error)
      throw new Error(error.response?.data?.message || '获取SLA达成率失败')
    }
  },

  // 批量操作
  async bulkAction(action, ticketIds, data = {}) {
    try {
      const response = await apiClient.post('/tickets/bulk', {
        action,
        ticketIds,
        data
      })
      
      if (response.success) {
        console.log('✅ 批量操作成功')
        return response.data
      } else {
        throw new Error(response.message || '批量操作失败')
      }
    } catch (error) {
      console.error('❌ 批量操作失败:', error)
      throw error
    }
  },

  // 获取工单详情
  async getDetail(ticketId) {
    try {
      const response = await apiClient.get(`/tickets/${ticketId}`)
      
      if (response.success) {
        console.log('✅ 获取工单详情成功')
        return response.data
      } else {
        throw new Error(response.message || '获取工单详情失败')
      }
    } catch (error) {
      console.error('❌ 获取工单详情失败:', error)
      throw error
    }
  },

  // 添加工单评论
  async addComment(ticketId, comment) {
    try {
      const response = await apiClient.post(`/tickets/${ticketId}/comments`, comment)
      
      if (response.success) {
        console.log('✅ 添加评论成功')
        return response.data
      } else {
        throw new Error(response.message || '添加评论失败')
      }
    } catch (error) {
      console.error('❌ 添加评论失败:', error)
      throw error
    }
  },

  // 添加工单附件
  async addAttachment(ticketId, file) {
    try {
      const formData = new FormData()
      formData.append('file', file)
      
      const response = await apiClient.post(`/tickets/${ticketId}/attachments`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      if (response.success) {
        console.log('✅ 添加附件成功')
        return response.data
      } else {
        throw new Error(response.message || '添加附件失败')
      }
    } catch (error) {
      console.error('❌ 添加附件失败:', error)
      throw error
    }
  },

  // 导出工单
  async export(filters = {}, format = 'excel') {
    try {
      const response = await apiClient.post('/tickets/export', {
        filters,
        format
      }, {
        responseType: 'blob'
      })
      
      console.log('✅ 导出工单成功')
      return response
    } catch (error) {
      console.error('❌ 导出工单失败:', error)
      throw error
    }
  },

  // 导入工单
  async import(file) {
    try {
      const formData = new FormData()
      formData.append('file', file)
      
      const response = await apiClient.post('/tickets/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      if (response.success) {
        console.log('✅ 导入工单成功')
        return response.data
      } else {
        throw new Error(response.message || '导入工单失败')
      }
    } catch (error) {
      console.error('❌ 导入工单失败:', error)
      throw error
    }
  }

}


